package com.kongchengji.zhanguafou.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kongchengji.zhanguafou.constant.OCRAccesstoken;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Service
public class OCRService {

    @Value("${pic.location}")
    private String picLocation;
    Logger logger = LoggerFactory.getLogger(OCRService.class);

    /**
     * 图片识别结果
     * @return
     */
    public String recognizePic(){
        String base64 = getBase64();
        RequestBody requestBody = new FormBody.Builder()
									.add("image",base64)
									.add("access_token", OCRAccesstoken.ACCESS_TOKEN)
				                    .build();
		Request request = new Request.Builder().post(requestBody)
				.addHeader("Content-Type","application/x-www-form-urlencoded")
				.post(requestBody)
				.url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic")
				.build();
		OkHttpClient client = new OkHttpClient();
		try {
		 Response response = client.newCall(request).execute();
		 String result = response.body().string();
		 JSONObject jsonObject = JSONObject.parseObject(result);
		 JSONArray wordsResult = (JSONArray)jsonObject.get("words_result");
		 String[] words = wordsResult.toJSONString().split(":");
		 //获得识别出的文字
		 String word = words[1];
		 StringBuilder stringBuilder = new StringBuilder();
		 //去除非数字和字母以外的字符
         Pattern pattern = Pattern.compile("[a-zA-Z]|[0-9]");
         Matcher matcher = pattern.matcher(word);
         while (matcher.find()){
             stringBuilder.append(matcher.group());
         }
		 return stringBuilder.toString();
		} catch (IOException e) {
		    logger.error("无法调用百度api");
			e.printStackTrace();
		}
		return null;
    }


    public String getBase64() {
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(picLocation+"image/code1.jpg"));
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(bytes);
        } catch (FileNotFoundException e) {
            logger.error("验证码图片位置错误");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("读取图片流抛出io异常");
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
